import { DrawerController, DrawerItem, createDrawerContainer } from '@ibiz/drawer-vue';
import { AppServiceBase, INavigationDesignModalContext, NavigationDesignModal } from '@ibizstudio/runtime';
import { isArray, notNilEmpty } from 'qx-util';
import { Subject, Observable } from 'rxjs';
import Vue from 'vue';

/**
 * 模态
 *
 * @export
 * @class AppPopup
 */
export class AppPopup {

    /**
     * store对象
     *
     * @protected
     * @memberof AppPopup
     */
    protected store: any;

    /**
     * i18n对象
     *
     * @protected
     * @memberof AppPopup
     */
    protected i18n: any;

    /**
     * 路由对象
     *
     * @protected
     * @memberof AppPopup
     */
    protected router: any;

    /**
     * 飘窗实例
     *
     * @protected
     * @type {DrawerItem[]}
     * @memberof AppPopup
     */
    protected drawerList: DrawerItem[] = [];

    /**
     * Creates an instance of AppPopup.
     * @memberof AppPopup
     */
    constructor() {
        this.initData();
    }

    /**
     * 初始化基础数据
     * 
     * @memberof AppPopup
     */
    protected initData(): void {
        if (!this.store) {
            const appService = AppServiceBase.getInstance();
            this.store = appService.getAppStore();
            this.i18n = appService.getI18n();
            this.router = appService.getRouter();
        }
    }


    /**
     * 添加飘窗实例
     *
     * @protected
     * @memberof AppPopup
     */
    protected addDrawerItem(item: DrawerItem): void {
        this.drawerList.push(item);
        this.store.commit('pushDrawerList', item);
        DrawerController.exp.setItems(this.drawerList);
    }

    /**
     * 移除指定飘窗实例
     *
     * @protected
     * @memberof AppPopup
     */
    protected removeDrawerItem(id: string): void {
        const i = this.drawerList.findIndex(item => item.id === id);
        this.drawerList.splice(i, 1);
        this.store.commit('removeDrawerList', i);
        DrawerController.exp.setItems(this.drawerList);
    }

    /**
     * 顶部抽屉模式打开视图
     *
     * @param {{ viewname: string, title: string, width?: number, height?: number }} view 视图
     * @param {*} [viewParam={}] 视图参数
     * @param {any[]} deResParameters 关系实体参数对象
     * @param {any[]} parameters 当前应用视图参数对象
     * @param {any[]} args 多项数据
     * @param {*} [data={}] 行为参数
     * @returns {Observable<any>}
     * @memberof AppTopDrawerContainer
     */
    openDrawer(
        view: { viewname: string; title: string; width?: number; height?: number; placement?: string },
        dynamicProps: any = {},
        staticProps: any = {},
    ): Observable<any> {
        this.initData();
        const subject: Subject<any> = new Subject();
        this.open(view, dynamicProps, staticProps).then((data: any) => {
            subject.next(data);
            subject.complete();
            subject.unsubscribe();
        });
        return subject.asObservable();
    }

    /**
     * 清除dc脏数据缓存信息
     *
     * @author zhanghengfeng
     * @date 2023-08-01 18:08:12
     * @param {NavigationDesignModal} navigationDesignModal
     * @param {INavigationDesignModalContext} context
     * @param {string} key
     */
    clearDcCache(navigationDesignModal: NavigationDesignModal, context: INavigationDesignModalContext, key: string) {
      if (context.key) {
        ___ibz___.dc.delete(context.key as string);
      }
      navigationDesignModal.clear(key);
    }

    /**
     * 打开上飘窗
     *
     * @protected
     * @param {{ viewname: string; title: string; width?: number; height?: number; placement?: string }} view
     * @param {*} [dynamicProps={}]
     * @param {*} [staticProps={}]
     * @return {*}  {Promise<any>}
     */
    protected async open(
        view: { viewname: string; title: string; width?: number; height?: number; placement?: string },
        dynamicProps: any = {},
        staticProps: any = {},
    ): Promise<any> {
        const obj = dynamicProps.navdatas[0];
        const srfmajortext = obj ? obj.srfmajortext : '';
        const viewParamData = dynamicProps.viewparam ?  JSON.parse(dynamicProps.viewparam) : undefined;
        const id = viewParamData?.srfparentkey ? viewParamData.srfparentkey : viewParamData?.srfkey;
        // 计算展示层级
        this.store.commit('upZIndex');
        const zIndex = this.store.getters.getZIndex();
        // 基本输入参数补充
        Object.assign(staticProps, { viewDefaultUsage: false, noViewCaption: true });
        const caption = srfmajortext ? srfmajortext : view.title;
        const navigationDesignModal = new NavigationDesignModal({ selection: id });
        const ref = await DrawerController.present({
          id,
          caption,
          overlayIndex: zIndex,
          component: createDrawerContainer({
            provide: {
              navigationDesignModal,
            },
          }) as any,
          componentProps: { store: this.store, i18n: this.i18n, router: this.router, propsData: { dynamicProps, staticProps } },
          beforeDismiss: async () => {
            const context = await navigationDesignModal.dismiss();
            if (context.allowClose) {
              this.clearDcCache(navigationDesignModal, context, id);
              return true;
            } else {
              return new Promise(resolve => {
                Vue.prototype.$Modal?.confirm({
                  width: 300,
                  render() {
                    return (
                      <div>
                        <div>
                          <icon type='ios-alert' color='#f90' size={20}></icon>
                          <span class='title' style='font-size: 16px;margin-left: 10px;'>
                            警告
                          </span>
                        </div>
                        <div style='text-align: center;margin-top: 12px;'>数据已变更, 请确认是否关闭?</div>
                      </div>
                    );
                  },
                  onOk: () => {
                    this.clearDcCache(navigationDesignModal, context, id);
                    resolve(true);
                  },
                  onCancel: () => {
                    resolve(false);
                  },
                });
              });
            }
          },
        });
        // 缓存打卡界面信息
        const self: DrawerItem = {
            id,
            ref,
            caption,
        };
        const i = this.drawerList.findIndex(item => item.id === id);
        if (i === -1) {
            this.addDrawerItem(self);
            // 侦听关闭行为
            const result = await ref.onDidDismiss();
            this.removeDrawerItem(self.id);
            this.store.commit('downZIndex');
            return { ret: notNilEmpty(result) ? 'OK' : 'NONE', datas: isArray(result) ? result : [result] };
        }
    }
}

// 模态服务控制器实例
export const appPopup: AppPopup = new AppPopup();
